#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>
#include "log.hpp"

using namespace LogModule;
static int number = 1;
class Thread
{
    static void *Routine(void *args);
    // 回调函数
    using func_t = std::function<void()>;

public:
    Thread(func_t func)
        : isrunning(false), isdetach(false), _func(func), _tid(-1)
    {
        _name = "Thread-" + std::to_string(number++);
    }
    ~Thread()
    {
    }
    void EnableRunning()
    {
        isrunning = true;
    }
    void EnableDetach()
    {
        isdetach = true;
    }
    void Detach()
    {
        if (isdetach)
        {
            int ret = pthread_detach(_tid);
            if (ret < 0)
            {
                LOG(LogLevel::ERROR) << "detach fail!";
            }
        }
        else
        {
            return;
        }
    }
    void Start()
    {
        if (isrunning)
        {
            return;
        }
        int ret = pthread_create(&_tid, nullptr, Routine, this);
        if (ret < 0)
        {
            LOG(LogLevel::ERROR) << "pthread_creat fail!";
        }
    }

private:
    static void *Routine(void *args)
    {
        Thread *self = static_cast<Thread *>(args);
        self->EnableRunning();

        self->_func();
    }
    pthread_t _tid;
    std::string _name;
    bool isrunning;
    bool isdetach;
    func_t _func;
};